#include <stdio.h>
#include <stdlib.h>
#include "bool.h"
#include "data.h"
#include "key.h"
#include "tuple.h"
#include "ListaAsoc.h"

struct sListaAsoc {
	tuple * array;
	int free;
	int size;
};

ListaAsoc la_empty (void) {
	ListaAsoc l = (ListaAsoc)calloc(1,sizeof(struct sListaAsoc));

	l->array = (tuple*)calloc(LIST_SIZE,sizeof(tuple));
	l->free = 0;
	l->size = LIST_SIZE;

	return l;
}

bool la_exists (ListaAsoc l, key k) {
	int i = 0;
	bool b = FALSE;

	while (i<l->free && !b){
		b = key_eq(k,tuple_fst(l->array[i]));
		i = i+1;
	}

	return b;
}

void la_add (ListaAsoc l, key k, data d) {
	if (l->free == (l->size)-1) {
		l->array = (tuple *)realloc(l->array,(2*(l->size))*sizeof(tuple));
		printf("|");
		if (l->array != NULL) {
			l->array[l->free] = tuple_fromKeyData(k,d);
			l->size=2*l->size;
			}
		}
	else {
		l->array[l->free] = tuple_fromKeyData(k,d);
	}
	(l->free)=(l->free)+1;
}

data la_search (ListaAsoc l, key k) {
	int i = 0;

	while (i < (l->size) && !(key_eq(k,tuple_fst(l->array[i])))) {
		i = i+1;
	}

	return (tuple_snd(l->array[i]));
}

void la_del (ListaAsoc l, key k) {
	int i = 0;

	while (i < (l->size) && !(key_eq(k,tuple_fst(l->array[i])))) {
		i = i+1;
	}

	l->array[i] = tuple_destroy(l->array[i]);

	while (i < (l->free)-1) {
		l->array[i]	= l->array[i+1];
		l->array[i+1] = NULL;
		i = i+1;
	}

	(l->free) = (l->free)-1;
}

int la_length (ListaAsoc l) {
	return (l->free);
}

void la_pprint (ListaAsoc l) {
	int i;
	char * p = NULL;
	char * q = NULL;

	for (i=0; i<l->free; i++) {
		p = (char*)calloc(key_lenght(tuple_fst(l->array[i]))+1,sizeof(char));
		key_toString(tuple_fst(l->array[i]),p);
		q = data_toString(tuple_snd(l->array[i]));
		printf("\n%s: %s \n \n",p,q);

		free(p);
		p = NULL;
		free(q);
		q = NULL;
	}
}

ListaAsoc la_destroy (ListaAsoc l) {
	int i;

	for (i=0 ; i<l->free; i++){
		l->array[i]=tuple_destroy(l->array[i]);
		}

	free (l->array);
	l->array = NULL;
	free (l);
	l = NULL;

	return l;
}


